<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/27
 * Time: 9:49
 */

namespace app\admin\controller;
use app\admin\Model\CommdityType;
use app\admin\Model\CommodityClassify;
use app\admin\Logic\CommodityClassLogic;
use app\admin\Model\CommodityType;
use app\Model\AdminModel;
use app\Model\BrandModel;
use app\Model\CommodityAttributeModel;
use app\Model\CommodityClassifyModel;
use app\Model\CommodityItemModel;
use app\Model\CommoditySpec;
use app\Model\CommoditySpecModel;
use app\Model\CommodityTypeModel;
use app\Model\GoodsAttrModel;
use app\Model\GoodsImagesModel;
use app\Model\GoodsModel;
use app\Model\SpecGoodsPriceModel;
use think\Controller;
use think\Paginator;
use think\Db;
use think\Request;
use think\Model;
class Goods extends Common
{

    /*
     * 商品列表
     */
    public function index()
    {
        $getData = input('get.');//搜索


        $where = [];

        //筛选
        if (isset($getData['cat_id'])){
            if ($getData['cat_id']!=-1){//分类
                $where['cat_id'] = ['=', $getData['cat_id']];
            }
            if ($getData['brand_id']!=-1){//品牌
                $where['brand_id'] = ['=', $getData['brand_id']];
            }
            if ($getData['is_on_sale']!=-1){//是否上架
                $where['is_on_sale'] = ['=', $getData['is_on_sale']];
            }
            if ($getData['is_new']!=-1){//是否新品
                $where['is_new'] = ['=', $getData['is_new']];
            }
            if ($getData['is_recommend']!=-1){//是否推荐
                $where['is_recommend'] = ['=', $getData['is_recommend']];
            }
            if ($getData['goods_name']!=-1){//商品名
                $where['goods_name'] = ['LIKE', '%'.$getData['goods_name'].'%'];
            }
        }
        $data['categoryList'] =  getSortCategory();//根据字母（A-Z）排序次级分类---商品分类
        $data['brand']=getSortBrands();//根据字母（A-Z）排序次级分类---品牌
        $data['data']= GoodsModel::where($where)->order('sort asc,goods_id desc')->paginate(10,false,['query'=>request()->param()]);
        $this->getConAndAct('Goods');
        return view('index',$data);
    }
    /*商品删除
     * */
    public function del(){
        $id=input('id');
        $file_url=GoodsModel::find($id);
        $this->del_file($file_url->original_img);//清除图片文件
        $file_urls=GoodsImagesModel::where('goods_id','=',$id)->select();
        GoodsImagesModel::where('goods_id','=',$id)->delete();
        foreach ($file_urls as $k=>$v){//清除图片文件(相册)
            $this->del_file($v->image_url);
        }
        $res=GoodsModel::destroy($id);
        return setDatabase($res,'删除');
    }
    /*
     * 商品添加、编辑页面(新)
     */
    public function add2()
    {
        $getData=input('get.');
        session('specData',0);
        $classify=  \app\Model\CommodityClassifyModel::where('parent_id','=',0)
            ->where('delete_time',null)
            ->select();

        $data['brand']=getSortBrands();//根据字母（A-Z）排序次级分类---品牌
        $data['classify'] = $classify; //商品分类（最高级）
        $data['type'] = CommodityTypeModel::select();
            if (isset($getData['goods_id'])){//是否传goods_id
                $where=['goods_id'=>$getData['goods_id']];
                $data['goods']=GoodsModel::find($getData['goods_id']);//商品信息
                $classify=CommodityClassifyModel::find($data['goods']->cat_id);//商品分类
                $parent= explode('_',$classify->parent_id_path);
                $data['parent']=$parent;
                foreach ($parent as $k=>$v){
                    $data['classifyd'][$k]=CommodityClassifyModel::where('parent_id','=',$v)->column('name','id');
                }
                $data['images']=GoodsImagesModel::where($where)->select(); //相册
//                $data['goods_type'];//商品属性类型id
                $data['attr'] = CommodityAttributeModel::where('type_id','=',$data['goods']->goods_type)
                    ->select();//商品属性详情表数据
                $data['goods_attr'] = GoodsAttrModel::where($where)->column('attr_value','attr_id');//商品属性值
                //规格表头
                $data['spec'] = CommoditySpecModel::where('type_id','=',$data['goods']->spec_type)
                    ->order('s_id','asc')
                    ->where('type_id','<>',0)
                    ->select();//规格类别
                foreach ($data['spec'] as $k=>$v){
                    $item=CommodityItemModel::where('spec_id','=',$v->s_id)->column('item','id');

                    $data['spec'][$k]['item']=$item;
                }

                //规格属性价格表
                $goods_spec=SpecGoodsPriceModel::where($where)
                    ->order('id','asc')
                    ->select();
                foreach ($goods_spec as $k=>$v){
                    $key= explode('-',$v->key);
                    $goods_spec[$k]['key']=$key;
                    $a=session('specData');
                    session('specData',$a+1);
                }
                $data['goods_spec']=$goods_spec;
                return view('goodsEdit',$data);//编辑页
            }else{
                return view('goodsAdd',$data);//添加页

            }
//        $data['classify']=getSortBrands();//根据字母（A-Z）排序次级分类---分类

    }
    /*
     *  商品添加、编辑 （新）
     */
    public function addData()
    {
        $getData=input('post.');

        if (end($getData['class'])==0){array_pop($getData['class']);}
        if (!$getData['class']){return retJson('',201,'请设置分类');}//没有设置分类
        //商品表添加/编辑
//        $goodsData2=[
//            ['cat_id',end($getData['class'])],'goods_sn','goods_name','brand_id','store_count','weight','market_price','shop_price','cost_price','commission1','commission2','keywords','goods_remark','is_free_shipping','goods_type','spec_type',['on_time',time()]];
//        $goodsData2=database_data_array($goodsData2,$getData);
        $goodsData=[
            'cat_id'=>end($getData['class']),//分类id
            'goods_sn'=>$getData['goods_sn'],//商品货号
            'goods_name'=>$getData['goods_name'],
            'brand_id'=>$getData['brand_id'],//品牌
            'store_count'=>$getData['store_count'],//库存
            'weight'=>$getData['weight'],//重量
            'market_price'=>$getData['market_price'],//市场价
            'shop_price'=>$getData['shop_price'],//本店价
            'cost_price'=>$getData['cost_price'],//商品成本价
            'commission1'=>$getData['commission1'],//第一上级佣金
            'commission2'=>$getData['commission2'],//第一上级佣金
            'keywords'=>$getData['keywords'],//商品关键词
            'goods_remark'=>$getData['goods_remark'],//商品描述（简单）
//            'goods_content'=>$getData['goods_content'],//商品描述（复杂）富文本编辑器
//            'original_img'=>$getData[''],//原始图
            'is_free_shipping'=>$getData['is_free_shipping'],//是否包邮0否 1是
            'goods_type'=>$getData['goods_type'],//属性类型id
            'spec_type'=>$getData['spec_type'],//规格类型id
//            'give_integral'=>$getData['give_integral'],//购买赠送积分
//            'exchange_integral'=>$getData['exchange_integral'],//兑换积分
            'on_time'=>time(),//上架时间
        ];

        $file = request()->file('original_img');//单图
        if ($file){//商品图片是否上传（单图）
            $goodsData['original_img']=$this->upload_files($file);
            if (isset($getData['goods_id'])){//1.检测原有图片文件
                $file_url=GoodsModel::find($getData['goods_id']);
                $this->del_file($file_url->original_img);//2.清除原有图片文件
            }
        }
        $files=request()->file('image');
        if (isset($getData['goods_id'])){//是否编辑
            sole('tp_goods',['goods_name'=>$getData['goods_name']],['goods_id',$getData['goods_id']],"商品名称");//判断修改账号是否存在

            $goodsData['goods_id']=$getData['goods_id'];//编辑商品id
            $setGoods=GoodsModel::update($goodsData);//编辑
        }else{
            sole('tp_goods',['goods_name'=>$getData['goods_name']],[],"商品名称");//判断修改账号是否存在

            $setGoods=GoodsModel::insertGetId($goodsData);//添加
        }
        setDatabaseDef($setGoods,'商品表添加失败');
        //商品相册表添加、编辑（删除）
        //判断是否有删除的图片
        if (isset($getData['image_url'])){//编辑进
            $files_url=GoodsImagesModel::
            where('image_url','not in',$getData['image_url'])
                ->where('goods_id','=',$getData['goods_id'])
                ->select();
            foreach ($files_url as $k=>$v){//清除图片文件(相册)
                $this->del_file($v->image_url);
            }
            $goodsImage = GoodsImagesModel::
                where('image_url','not in',$getData['image_url'])
                ->where('goods_id','=',$getData['goods_id'])
                ->delete();
        }
        if ($files){//上传相册进（多图）
        foreach ($files as $k=>$v){
            if (isset($getData['goods_id'])){//编辑进
                $images[$k]['goods_id']=$getData['goods_id'];//编辑商品id
            }else{//新增
                $images[$k]['goods_id']=$setGoods;//添加商品自增id
            }
            $images[$k]['image_url']=$this->upload_files($v);//返回路径
            //添加相册到商品图片表
        }
        $GoodsImages=new GoodsImagesModel();
        $setGooIm= $GoodsImages->saveAll($images);//商品相册批量添加
//            setDatabaseDef($setGooIm,'商品相册批量操作失败');
        //
    }
        //商品属性添加/编辑
        if (isset($getData['goods_id'])){//编辑进
            //编辑先清空原有属性
            $where=['goods_id'=>$getData['goods_id']];
            $getGoodsAttr= GoodsAttrModel::where($where)->find();
            if ($getGoodsAttr){
                $delGoodsAttr= GoodsAttrModel::where($where)->delete();
//                setDatabaseDef($delGoodsAttr,'清空原有属性失败');
            }
            //编辑清空原有规格价格
            $getSpecGoods = SpecGoodsPriceModel::where($where)->find();
            if ($getSpecGoods){
                $delSpecGoods = SpecGoodsPriceModel::where($where)->delete();
//                setDatabaseDef($delSpecGoods,'清空原有属性失败');
            }
        }
        if (isset($getData['attr'])){//是否有添加属性
            $setAttr=[];
            foreach ($getData['attr'] as $k=>$v){
                if ($v!=''){
                    $attr=[

                        'goods_id'=>$setGoods,//自增id
                        'attr_id'=>$k,//属性id
                        'attr_value'=>$v,//属性值
//                        'attr_price'=>0,//属性价格
                    ];
                    if (isset($getData['goods_id'])){
                        $attr['goods_id']= $getData['goods_id'];
                    }
                    array_push($setAttr,$attr);
                }
            }
//            dump($setAttr);
            $GoodsAttr=new GoodsAttrModel();
            $setGoodsAttr= $GoodsAttr->saveAll($setAttr);//商品属性批量添加
//            setDatabaseDef($setGoodsAttr,'商品属性批量添加失败');
        }
        //商品规格表添加

        $getCommoditySpec=CommoditySpecModel::column('spec_name','s_id');
        $getCommodityItem=CommodityItemModel::column('item','id');
        $spec=[];//存放单条tp_spec_goods_price表数据
        $spec_goods_price=[];//多条

        if (isset($getData['spec'])){//商品是否有规格
            foreach($getData['spec'] as $k=>$v){
                if (isset($v['key'])){
                    $item=[];
                    foreach($v['key'] as $key=>$value){
                        $spec_item=$getCommoditySpec[$key].':'.$getCommodityItem[$value];
                        array_push($item,$spec_item);
                    }

                    $spec['goods_id']=$setGoods;//商品id
                    asort($v['key']);
                    $spec['key']= implode($v['key'],'-');//key  规格键名
                    $spec['key_name']= implode($item,'-');//key_name  规格键名中文
                }

                if (isset($getData['goods_id'])){//编辑进
                    $spec['goods_id']= $getData['goods_id'];//需要编辑的商品id
                }
                $spec['price_tall']=$v['price_tall'];//原价格
                $spec['price']=$v['price'];//现价格
                $spec['store_count']=$v['store_count'];//库存数量
                $spec['price_internal']=$v['price_internal'];//库存单位
                array_push($spec_goods_price,$spec);
            }
            $SpecGoods=new SpecGoodsPriceModel;
            $setSpecGoods=$SpecGoods->saveAll($spec_goods_price);//批量添加规格价格
//            setDatabaseDef($setSpecGoods,'批量添加规格价格');
        }
        return retJson('',200,'操作成功');
    }


    /*
     * 根据不同商品类型打印商品属性填写框
     */
    public function inputAttr()
    {
        $getData= input('post.');
        $where=['type_id'=>$getData['type_id']];
        $getAttr=CommodityAttributeModel::where($where)->select();
        $html='';
        if ($getAttr){
            foreach ($getAttr as $k=>$v){
                    $html.='<tr >
                            <td> '.$v->attr_name.'</td>
                            <td><input type="text" size="40" value="" name="attr['.$v->attr_id.']"></td>
                        </tr>';
            }
        }
//        dump($html);
        echo $html;

    }
    /*
     * 根据不同商品类型打印商品规格
     */
    public function buttonSpec()
    {
        $getData= input('post.');
        $where =['type_id'=>$getData['type_id']];
        $spec= CommoditySpecModel::where($where)->where('type_id','<>',0)->select();//规格类

        $html='<tr>
                    <td colspan="2"><b>商品规格:</b></td>
                </tr>';
       if ($spec){
           foreach ($spec as $k=>$v){
                $htmld='';//存放规格详情信息
                $whered=['spec_id'=>$v->s_id];
                $item=CommodityItemModel::where($whered)->select();//详细规格（例：白色、黑色）
                if ($item){
                    foreach ($item as $key=>$value){
                        $htmld.=' <button type="button" onclick="inputSpec(this)" data-spec_id="'.$v->s_id.'" data-item_id="'.$value->id.'" class="btn btn-success">'.$value->item.'</button>';
                    }
                }
               $html.='
                        
                        <tr>
                            <td>'.$v->spec_name.':</td>
                            <td>
                                '.$htmld.'
                            </td>
                        </tr>';

           };
       }

       echo $html;
    }

   /*
    * 根据选中规格打印输入表头
    */
    public function inputSpec()
    {
        $getData= input('post.');
        $htmlThead='';//表头

        $gerSepc = CommoditySpecModel::where('type_id','in',$getData['type_id'])->order('s_id','asc')->select();
        foreach ($gerSepc as $k=>$v){//规格种类（例：大小、颜色、产的）
            $htmlThead.='<td><b>'.$v->spec_name.'</b></td>
                        ';


        }
        $htmlThead='<tr>
                        '.$htmlThead.'
                        <td><b>原价</b></td>
                        <td><b>现价</b></td>
                        <td><b>库存</b></td>
                        <td><b>内部价</b></td>
                        <td><b>操作</b></td>
                   </tr>';



        //规格详细属性和输入框（例；黑色、白色）
//        每一个规格都需要一层遍历
        
        echo $htmlThead;
    }
    /*
     * 根据选中规格打印输入表身
     */
    public function inputSpecbody()
    {
        $getData= input('post.');
        $a=session('specData');
        session('specData',$a+1);
        $gerSepc = CommoditySpecModel::where('type_id','in',$getData['type_id'])->order('s_id','asc')->select();
        $htmlTbody='';
        //是否有规格分类
        $get_item=CommoditySpecModel::where('type_id','in',$getData['type_id'])->find();
        if (!$get_item){
           return false;
        }
        $htmlTbody.='<tr>';
        foreach ($gerSepc as $k=>$v){
            $getItem= CommodityItemModel::where('spec_id','=',$v->s_id)->select();

            $htmlTbody.='<td><b>
                           <select name="spec['.$a.'][key]['.$v->s_id.']" >';
                           foreach ($getItem  as $key=>$value){
                               $htmlTbody.='<option value="'.$value->id.'">'.$value->item.'</option>';
                           }
            $htmlTbody.='  </select>
                        </b></td>';

        }
        $htmlTbody.='<td><b><input calss="form-control" type="number" name="spec['.$a.'][price_tall]"     value="0.00" ></b></td>';//价格
        $htmlTbody.='<td><b><input calss="form-control" type="number" name="spec['.$a.'][price]"          value="0.00" ></b></td>';//价格
        $htmlTbody.='<td><b><input calss="form-control" type="number" name="spec['.$a.'][store_count]"    value="0"  count="count" ></b></td>';//库存
        $htmlTbody.='<td><b><input calss="form-control" type="number" name="spec['.$a.'][price_internal]" value="0.00" ></b></td>';//内部价
        $htmlTbody.='<td><b><a onclick="del_tbody(this);" class="tpl-table-black-operation-del">
                                                    <i class="am-icon-trash"></i> 删除
                                                </a></b></td>';
        $htmlTbody.='<tr>';
        echo $htmlTbody;
    }

    //商品分类
   public function commodityclassify(){
       $CommodityClassLogic = new CommodityClassLogic();
       $goods_category=CommodityClassifyModel::where('delete_time',null)
//           ->order('parent_id asc,sort_order desc')
           ->paginate();
//       $cat_list = $CommodityClassLogic->goods_cat_list();
//       $this->assign('cat_list',$cat_list);
       $this->assign('goods_category',$goods_category);
       $this->getConAndAct('Goods');
       return $this->fetch('commodityClassify');
 }

 /*
  * 商品分类添加、编辑页面（新）
  */
    public function classifyAdd()
    {
        $getData=input('get.');
        //顶级分类
        $data['classt'] = CommodityClassifyModel::where('parent_id','=',0)
            ->where('delete_time',null)
            ->select();
        if (isset($getData['id'])){//编辑
            $data['comm']=CommodityClassifyModel::find($getData['id']);//分类信息
            //家族图谱
//            $data['parent_id_path']=explode('-',$data['comm']->parent_id_path);
            $parent_id_path=explode('_',$data['comm']->parent_id_path);
            $data['classid']=$parent_id_path;
            array_pop($parent_id_path);//删除最后个无用数据（自身id）
            foreach ($parent_id_path as $k=>$v){
                $where=['parent_id'=>$v];
                $Comm=CommodityClassifyModel::where($where)->select();//该属于$v的所有分类
                $parent_id_path[$k]=$Comm->toArray();
            }
            $data['parent_id_path']=$parent_id_path;
            return view('classifyEdit',$data);

        }

        //
        return view('classifyAdd',$data);
   }
   /*
    * 返回所属子分类--商品分类
    * $parent_id(父id)
    */
    public function subclass()
    {
        $getData=input('post.');
        $parent_id=$getData['parent_id'];
        $subclass= CommodityClassifyModel::where('parent_id','=',$parent_id)
            ->where('delete_time',null)
            ->select();
        $html='';

        if(isset($subclass[0])){
            foreach($subclass as $h){
                $html .= "<option value='{$h['id']}'>{$h['name']}</option>";
            }
        }
        $htmlm = "<div class='am-u-sm-2'>
                            <select  name='class[]' onchange='subclass(this)'>
                            <option value='0' selected >创建新的分类</option>
                            ".$html."
                             </select>
                      </div>";
        $html=$htmlm;
//        dump($html);
        echo $html;
    }

    /*
     * 返回所属子分类--商品
     */
    public function subclassGoods()
    {
        $getData=input('post.');
        $parent_id=$getData['parent_id'];
        $subclass= CommodityClassifyModel::where('parent_id','=',$parent_id)
            ->where('delete_time',null)
            ->select();
        $html='';

        if(isset($subclass[0])){
            foreach($subclass as $h){
                $html .= "<option value='{$h['id']}'>{$h['name']}</option>";
            }
            $htmlm = "<div class='am-u-sm-2'>
                     <select name='class[]' id='cat_id' onchange='subclass(this);' class='form-control' style='margin-left:-15px;'>
                     <option value='0'>选择分类</option>
                            ".$html."
                     </select>
                  </div>";
        }
        $html=$htmlm;
//        dump($html);
        echo $html;
    }


    /*
     * 商品分类添加、编辑  (新)
     */
    public function classifyAddData()
    {
        $file = request()->file('image');
        $getData=input('post.');
        array_unshift($getData['class'],0);

        array_pop($getData['class']);//删除最后

        $parent_id_path=$getData['class'];//将家族图谱数组储存
        $parent_id=end($getData['class']);// 数组最后一个元素
        $getData['parent_id']=$parent_id;//父id
        unset($getData['class']);//去除分类组
        if ($file){//是否上传图片
            $getData['image']=$this->upload_files($file);
            if ($getData['id']){//1.检测原有图片文件
                $CommImg=CommodityClassifyModel::find($getData['id']);
                $this->del_file($CommImg->image);//2.清除原有图片文件
            }
        }
        if ($getData['id']){//编辑
            sole('commodity_classify',['name'=>$getData['name']],['id',$getData['id']],"商品分类名称");//判断修改分类是否存在
//            $getComm=CommodityClassifyModel::find($getData['id']);
            array_push($parent_id_path,$getData['id']);
            $getData['parent_id_path']=implode('_',$parent_id_path);//家族图谱
            $setComm=CommodityClassifyModel::update($getData);
        }else{//新增
            sole('commodity_classify',['name'=>$getData['name']],['id',$getData['id']],"商品分类名称");//判断分类名称是否存在
            $addComm = CommodityClassifyModel::insertGetId($getData);
            setDatabaseDef($addComm,'添加失败');
            //补充家族图谱
            array_push($parent_id_path,$addComm);//自增id 推入家族最后一位
            $updata['parent_id_path']=implode('_',$parent_id_path);//家族图谱

            $setComm=CommodityClassifyModel::where('id','=',$addComm)->update($updata);
        }
        return setDatabase($setComm);
    }
    //分类删除
    public function commodityClassifyDelete(){
        $id=input('id');
        $arr=array();
       $getGoods=GoodsModel::where('cat_id','=',$id)->find();//该分类下有商品时不能删
        if ($getGoods){
            return retJson('',201,'该分类存在商品无法删除');
        }
        $getClass=  CommodityClassifyModel::where('parent_id','=',$id)->find(); //有子分类的情况不能删除
      if ($getClass){
          return retJson('',201,'该分类存在子分类无法删除');
      }
        $CommImg=CommodityClassifyModel::find($id);
        $this->del_file($CommImg->image);//2.清除原有图片文件
        $res=CommodityClassifyModel::delete($id);
        return setDatabase($res,'删除');
    }
    //商品类型
    public function commoditytype(){
        $cat_list = CommodityTypeModel::order("id desc")->paginate(20);
        $this->assign('cat_list',$cat_list);
        $this->getConAndAct('Goods');
        return $this->fetch('commodityType');
    }
    /**
     * 添加修改商品类型
     * @id id 商品类型的id
     */
    public function commodityTypeAdd(){
        $id=input('id');
        if(Request::instance()->isGet()) {
            $cat_list = Db('commodity_type')->where('id', $id)->find();
            $this->assign('cat_list', $cat_list);
            return view('commodityTypeAdd');
        }
        $name=input('name');
        $data=['name'=>$name];
       if(!empty($id)){
             sole('commodity_type',['name'=>$name],['id',$id],"商品类型");//判断修改商品类型是否存在
             $res=Db('commodity_type')->where('id',$id)->update($data);
       }else{
             sole('commodity_type',['name'=>$name],[],"商品类型");//判断修改商品类型是否存在
             $res=Db('commodity_type')->insert($data);

       }
       return setDatabase($res);

    }
//商品类型软删除
    public function commodityTypeDelete(){
        $id=input('id');
        $arr=array();
        $res=CommodityTypeModel::destroy($id);

        if ($res){
            return retJson('',200,'删除成功');
        }else{
            return retJson('',201,'删除失败');
        }
    }
  public function change(){
        $is =input('is');
      $goods_id=input('goods_id');
       switch (input('type')){
           case 'is_on_sale':
              $type =['is_on_sale' =>$is];
            break;
           case 'is_recommend':
               $type =['is_recommend' =>$is];
               break;
           case 'is_new':
               $type =['is_new' =>$is];
               break;
           case 'is_hot':
               $type =['is_hot' =>$is];
               break;
       }
      $info  = GoodsModel::update($type, ['goods_id' => $goods_id]);
      if ($info){
          return retJson('',200,'修改成功');
      }else{
          return retJson('',201,'修改失败');
      }
  }

}